import {
  USER_LOGIN_REQUEST,
  USER_LOGIN_SUCCESS,
  USER_LOGIN_FAIL,
  USER_LOGIN_OUT,
  USER_REGISTER_REQUEST,
  USER_REGISTER_SUCCESS,
  USER_REGISTER_FAIL,
  USER_DETAILS_REQUEST,
  USER_DETAILS_SUCCESS,
  USER_DETAILS_FAIL,
  USER_UPDATE_REQUEST,
  USER_UPDATE_SUCCESS,
  USER_UPDATE_FAIL,
  USER_LIST_REQUEST,
  USER_LIST_SUCCESS,
  USER_LIST_FAIL,
  USER_LIST_RESET,
  USER_DELETE_REQUEST,
  USER_DELETE_SUCCESS,
  USER_DELETE_FAIL,
  USER_ADMIN_UPDATE_REQUEST,
  USER_ADMIN_UPDATE_SUCCESS,
  USER_ADMIN_UPDATE_FAIL,
  USER_ADMIN_UPDATE_RESET,
  USER_DETAILS_RESET,
} from "../constants/userConstants";
import { ORDER_LIST_MY_RESET } from "../constants/orderConstants";
import axios from "axios";

//用户登录
export const login = (email, password) => async (dispatch) => {
  try {
    dispatch({ type: USER_LOGIN_REQUEST });
    // 设置请求头，使用json字符串发送请求
    const config = {
      headers: {
        "Content-Type": "application/json",
      },
    };
    //发送登录请求
    const { data } = await axios.post(
      "/api/users/login",
      { email, password },
      config
    );
    //登录成功，传输数据到reducer
    dispatch({ type: USER_LOGIN_SUCCESS, payload: data });
    //保存登录信息到本地
    localStorage.setItem("userInfo", JSON.stringify(data));
  } catch (error) {
    //登录失败
    dispatch({
      type: USER_LOGIN_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

//用户退出
export const logout = () => (dispatch) => {
  //移除保存在本地的登录用户信息
  localStorage.removeItem("userInfo");
  dispatch({ type: USER_LOGIN_OUT });
  dispatch({ type: USER_LIST_RESET });
  dispatch({ type: USER_DETAILS_RESET });
  dispatch({ type: ORDER_LIST_MY_RESET });
  document.location.href = "/login";
};

//用户注册
export const register = (name, email, password) => async (dispatch) => {
  try {
    dispatch({ type: USER_REGISTER_REQUEST });
    // 设置请求头，使用json字符串发送请求
    const config = {
      headers: {
        "Content-Type": "application/json",
      },
    };
    //发送注册请求
    const { data } = await axios.post(
      "/api/users",
      { name, email, password },
      config
    );
    //注册成功相当于登录成功，传输数据到reducer
    dispatch({ type: USER_REGISTER_SUCCESS, payload: data });
    dispatch({ type: USER_LOGIN_SUCCESS, payload: data });
    //保存登录信息到本地
    localStorage.setItem("userInfo", JSON.stringify(data));
  } catch (error) {
    //注册失败
    dispatch({
      type: USER_REGISTER_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

//用户详情
export const getUserDetails = (id) => async (dispatch, getState) => {
  try {
    dispatch({ type: USER_DETAILS_REQUEST });

    //获取当前登录的用户信息
    const {
      userLogin: { userInfo },
    } = getState();

    // 设置请求头，设置token，使用json字符串发送请求
    const config = {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${userInfo.token}`,
      },
    };
    //根据id查询用户
    const { data } = await axios.get(`/api/users/${id}`, config);

    //查询成功，传输数据到reducer
    dispatch({ type: USER_DETAILS_SUCCESS, payload: data });
  } catch (error) {
    //注册失败
    dispatch({
      type: USER_DETAILS_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

//更新用户
export const updateUserDetails = (user) => async (dispatch, getState) => {
  try {
    dispatch({ type: USER_UPDATE_REQUEST });

    //获取当前登录的用户信息
    const {
      userLogin: { userInfo },
    } = getState();

    // 设置请求头，设置token，使用json字符串发送请求
    const config = {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${userInfo.token}`,
      },
    };
    //根据id更新用户
    const { data } = await axios.put(`/api/users/profile`, user, config);

    //更新成功，传输数据到reducer
    dispatch({ type: USER_UPDATE_SUCCESS, payload: data });
  } catch (error) {
    //注册失败
    dispatch({
      type: USER_UPDATE_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

//用户列表
export const listUsers = () => async (dispatch, getState) => {
  try {
    dispatch({ type: USER_LIST_REQUEST });

    //获取当前登录的用户信息
    const {
      userLogin: { userInfo },
    } = getState();

    // 设置请求头，设置token，使用json字符串发送请求
    const config = {
      headers: {
        Authorization: `Bearer ${userInfo.token}`,
      },
    };
    //查询所有用户
    const { data } = await axios.get(`/api/users`, config);

    //查询成功，传输数据到reducer
    dispatch({ type: USER_LIST_SUCCESS, payload: data });
  } catch (error) {
    //查询失败
    dispatch({
      type: USER_LIST_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

//删除用户
export const deleteUser = (id) => async (dispatch, getState) => {
  try {
    dispatch({ type: USER_DELETE_REQUEST });

    //获取当前登录的用户信息
    const {
      userLogin: { userInfo },
    } = getState();

    // 设置请求头，设置token，使用json字符串发送请求
    const config = {
      headers: {
        Authorization: `Bearer ${userInfo.token}`,
      },
    };
    //删除用户
    await axios.delete(`/api/users/${id}`, config);

    //删除成功，传输数据到reducer
    dispatch({ type: USER_DELETE_SUCCESS });
  } catch (error) {
    //删除失败
    dispatch({
      type: USER_DELETE_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

//管理员更新用户
export const adminUpdateUser = (user) => async (dispatch, getState) => {
  try {
    dispatch({ type: USER_ADMIN_UPDATE_REQUEST });

    //获取当前登录的用户信息
    const {
      userLogin: { userInfo },
    } = getState();

    // 设置请求头，设置token，使用json字符串发送请求
    const config = {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${userInfo.token}`,
      },
    };
    //管理员更新用户
    const { data } = await axios.put(`/api/users/${user._id}`, user, config);

    //更新成功，传输数据到reducer
    dispatch({ type: USER_ADMIN_UPDATE_SUCCESS, payload: data });
    dispatch({ type: USER_DETAILS_SUCCESS, payload: data });
  } catch (error) {
    //更新失败
    dispatch({
      type: USER_ADMIN_UPDATE_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};
